#include "MessageSystem.h"
#include "Message.h"

MessageSystem::MessageSystem(void){}

MessageSystem::~MessageSystem(void) { clearMessages(); }

MessageSystem* MessageSystem::m_instance = nullptr;

MessageSystem& MessageSystem::getSingleton()
{
	if (m_instance == nullptr)
		m_instance = new MessageSystem;
	return *m_instance;
}

void MessageSystem::clean()
{
	if (m_instance != nullptr)
	{
		delete m_instance;
		m_instance = nullptr;
	}
}

void MessageSystem::unregister(const std::string& p_subject, void* p_object)
{
	auto it = m_subjects[p_subject].begin();
	while (it != m_subjects[p_subject].end())
	{
		if ((*it)->isObject(p_object))
		{
			delete (*it);
			m_subjects[p_subject].erase(it);
			break;
		}
		it++;
	}
}

void MessageSystem::notify(const std::string& p_subject, Message* p_data)
{
	if (m_subjects[p_subject].empty())
		return;
	auto it = m_subjects[p_subject].begin();
	while (it != m_subjects[p_subject].end())
	{
		(*it)->notify(p_subject, p_data);
		it++;
	}
}

inline void MessageSystem::clearMessages()
{
	for (auto it = m_subjects.begin(); it != m_subjects.end(); it++)
	{
		for (auto it2 = (*it).second.begin(); it2 != (*it).second.end(); it2++)
		{
			delete (*it2);
			(*it2) = nullptr;
		}
		(*it).second.clear();
	}
	m_subjects.clear();
}